<template>
    <el-dialog v-model="visible" :style="{ margin: '0 auto', maxWidth: '1000px', width: '90%', overflowX: 'hidden' }"
        :append-to-body="true">

        <h2 class="title">未绑定客户查询</h2>

        <!-- 查询表单 -->
        <el-form :inline="true" :model="unlinkedQuery" class="search-bar">
            <el-form-item label="客户名：">
                <el-input v-model="unlinkedQuery.name" placeholder="请输入客户名" clearable />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="handleUnlinkedSearch">查询</el-button>
                <el-button type="default" @click="resetUnlinked">重置</el-button>
            </el-form-item>
        </el-form>

        <!-- 无管家客户列表 -->
        <h3 class="subtitle">无管家客户列表</h3>
        <el-table :data="excludedList" border style="width: 100%; background: #f5f7fa;" v-loading="loading.excluded"
            :header-cell-style="{ background: '#f9fafc', color: '#333', textAlign: 'center' }"
            :cell-style="{ textAlign: 'center' }">
            <el-table-column type="index" label="序号" width="60" />
            <el-table-column prop="name" label="姓名" />
            <el-table-column prop="age" label="年龄" />
            <el-table-column prop="gender" label="性别" />
            <el-table-column prop="bedId" label="床号" />
            <el-table-column label="操作" width="100">
                <template #default="scope">
                    <el-button type="success" size="small" @click="handleAddClient(scope.row)">添加</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 未绑定客户分页 -->
        <div class="pagination-bar">
            <el-pagination v-model:current-page="unlinkedPage.cur" v-model:page-size="unlinkedPage.size"
                :total="unlinkedPage.total" layout="total, sizes, prev, pager, next, jumper" :page-sizes="[5, 10, 20]"
                @size-change="fetchUnlinked" @current-change="fetchUnlinked" />
        </div>
        <!-- 已绑定客户列表 -->
        <h3 class="subtitle">管家客户列表</h3>
        <el-table :data="includedList" border style="width: 100%; background: #f5f7fa; margin-top: 20px;"
            v-loading="loading.included"
            :header-cell-style="{ background: '#f9fafc', color: '#333', textAlign: 'center' }"
            :cell-style="{ textAlign: 'center' }">
            <el-table-column type="index" label="序号" width="60" />
            <el-table-column prop="name" label="姓名" />
            <el-table-column prop="age" label="年龄" />
            <el-table-column prop="gender" label="性别" />
            <el-table-column prop="bedId" label="床号" />
            <el-table-column label="操作" width="100">
                <template #default="scope">
                    <el-button type="danger" size="small" @click="handleRemoveClient(scope.row)">移除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 已绑定客户分页 -->
        <div class="pagination-bar">
            <el-pagination v-model:current-page="includedPage.cur" v-model:page-size="includedPage.size"
                :total="includedPage.total" layout="total, sizes, prev, pager, next, jumper" :page-sizes="[5, 10, 20]"
                @size-change="fetchLinked" @current-change="fetchLinked" />
        </div>
    </el-dialog>
</template>

<script setup>
import { ref, defineExpose } from 'vue'
import {inject} from 'vue'
const axios = inject("axios")
import { ElMessage } from 'element-plus'
import qs from 'qs'

const visible = ref(false)
const userId = ref(null)
const username = ref('')
const unlinkedQuery = ref({ name: '' })
const linkedQuery = ref({ name: '' })
const excludedList = ref([])
const includedList = ref([])
const loading = ref({ excluded: false, included: false })
// 顶部添加两个分页对象
const unlinkedPage = ref({ cur: 1, size: 5, total: 0 })
const includedPage = ref({ cur: 1, size: 5, total: 0 })

const open = (id, name) => {
    userId.value = id
    username.value = name
    visible.value = true
    unlinkedQuery.value.name = ''
    linkedQuery.value.name = ''
    fetchData()
}

const fetchData = () => {
    fetchUnlinked()
    fetchLinked()
}

// fetchUnlinked 中添加分页参数处理
const fetchUnlinked = async () => {
    loading.value.excluded = true
    try {
        const res = await axios.get('/caretakerClient/caretakerClient', {
            params: {
                cur: unlinkedPage.value.cur,
                number: unlinkedPage.value.size,
                name: unlinkedQuery.value.name
            }
        })
        if (res.data.status === 200) {
            excludedList.value = res.data.data || []
            unlinkedPage.value.total = res.data.total || 0
        }
    } catch {
        ElMessage.error('加载未绑定客户失败')
    } finally {
        loading.value.excluded = false
    }
}

// fetchLinked 中添加分页参数处理
const fetchLinked = async () => {
    loading.value.included = true
    try {
        const res = await axios.get('/caretakerClient/getIncludedClients', {
            params: {
                cur: includedPage.value.cur,
                number: includedPage.value.size,
                userId: userId.value
            }
        })
        if (res.data.status === 200) {
            includedList.value = res.data.data || []
            includedPage.value.total = res.data.total || 0
        }
    } catch {
        ElMessage.error('加载已绑定客户失败')
    } finally {
        loading.value.included = false
    }
}


const handleAddClient = async (client) => {
    try {
        const res = await axios.post(
            '/caretakerClient/addClientToUser',
            qs.stringify({ userId: userId.value, clientId: client.clientId }),
            { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
        )
        if (res.data.status === 200) {
            ElMessage.success('添加成功')
            fetchData()
        } else {
            ElMessage.error(res.data.msg || '添加失败')
        }
    } catch (e) {
        ElMessage.error('添加失败：' + e.message)
    }
}

const handleRemoveClient = async (client) => {
    try {
        const res = await axios.post(
            '/caretakerClient/removeClientFromUser',
            qs.stringify({ userId: userId.value, clientId: client.clientId }),
            { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
        )
        if (res.data.status === 200) {
            ElMessage.success('移除成功')
            fetchData()
        } else {
            ElMessage.error(res.data.msg || '移除失败')
        }
    } catch (e) {
        ElMessage.error('移除失败：' + e.message)
    }
}

const resetUnlinked = () => {
    unlinkedQuery.value.name = ''
    fetchUnlinked()
}

const handleUnlinkedSearch = () => {
    unlinkedPage.value.cur = 1
    fetchUnlinked()
}


defineExpose({ open })
</script>

<style scoped>
.title {
    font-size: 27.2px;
    font-weight: bold;
    margin-bottom: 16px;
    color: #333;
}

.subtitle {
    font-size: 18px;
    font-weight: 500;
    margin: 20px 0 10px 0;
    color: #333;
}

.search-bar {
    display: flex;
    gap: 10px;
    margin-bottom: 16px;
    align-items: center;
}

.el-table th {
    text-align: center;
    background-color: #f9fafc;
    color: #333;
}

.el-table td {
    text-align: center;
}

.pagination-bar {
    display: flex;
    justify-content: flex-end;
    margin-top: 2%;
    margin-bottom: 2%;
}

/* scoped 或 global 中写 */
.custom-dialog {
    max-width: 1000px;
    margin: auto !important;
    /* 居中对齐 */
    overflow-x: hidden;
}

.el-dialog {
    box-sizing: border-box;
}
</style>
